import React, { useState, useCallback } from 'react';
import { Modal, Form, Button, Space } from 'antd';
import { useTranslation } from 'react-i18next';
import { notification } from '../../components/common'; // 导入自定义通知组件
import type { FormInstance } from 'antd/es/form';

type FormMode = 'create' | 'edit' | 'view';

interface FormModalProps {
  title?: string;
  visible: boolean;
  mode: FormMode;
  width?: number;
  initialValues?: Record<string, any>;
  onCancel: () => void;
  onSubmit?: (values: Record<string, any>) => Promise<void> | void;
  children: React.ReactNode;
  submitText?: string;
  cancelText?: string;
  loading?: boolean;
  formProps?: any;
}

const FormModal: React.FC<FormModalProps> = ({
  title,
  visible,
  mode,
  width = 600,
  initialValues,
  onCancel,
  onSubmit,
  children,
  submitText,
  cancelText,
  loading = false,
  formProps = {},
}) => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);

  // 获取默认标题
  const getDefaultTitle = useCallback(() => {
    const modeMap = {
      create: t('common.form.create'),
      edit: t('common.form.edit'),
      view: t('common.form.view'),
    };
    return modeMap[mode];
  }, [mode, t]);

  // 处理表单提交
  const handleSubmit = useCallback(async () => {
    if (mode === 'view') {
      onCancel();
      return;
    }

    try {
      const values = await form.validateFields();
      setSubmitting(true);
      
      if (onSubmit) {
        await onSubmit(values);
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: mode === 'create' ? t('common.form.create') : t('common.form.edit'),
          message: mode === 'create' 
            ? t('common.message.createSuccess')
            : t('common.message.updateSuccess')
        });
        onCancel();
      }
    } catch (error) {
      console.error('Form validation failed:', error);
      // 使用自定义通知组件替换 message.error
      notification.error({
        title: '表单验证失败',
        message: t('common.message.validateFailed')
      });
    } finally {
      setSubmitting(false);
    }
  }, [form, mode, onSubmit, onCancel, t]);

  // 处理取消
  const handleCancel = useCallback(() => {
    form.resetFields();
    onCancel();
  }, [form, onCancel]);

  // 渲染底部按钮
  const renderFooter = useCallback(() => {
    if (mode === 'view') {
      return [
        <Button key="close" onClick={handleCancel}>
          {cancelText || t('common.close')}
        </Button>
      ];
    }

    return [
      <Button key="cancel" onClick={handleCancel}>
        {cancelText || t('common.cancel')}
      </Button>,
      <Button 
        key="submit" 
        type="primary" 
        loading={submitting || loading}
        onClick={handleSubmit}
      >
        {submitText || (mode === 'create' ? t('common.create') : t('common.save'))}
      </Button>
    ];
  }, [mode, submitting, loading, handleCancel, handleSubmit, submitText, cancelText, t]);

  return (
    <Modal
      title={title || getDefaultTitle()}
      open={visible}
      width={width}
      footer={renderFooter()}
      onCancel={handleCancel}
      destroyOnClose
      maskClosable={false}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        disabled={mode === 'view'}
        {...formProps}
      >
        {children}
      </Form>
    </Modal>
  );
};

export default FormModal;